import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AppService} from '../../service/app/app.service';
import {PlatformLocation} from '@angular/common';

@Component({
  selector: 'app-splash',
  templateUrl: './splash.component.html',
  styleUrls: ['./splash.component.css']
})
export class SplashComponent implements OnInit {
  show = false;
  splashImg = require('../../../assets/image_bg.png');
  constructor(private router: Router,
              private location: PlatformLocation,
              private appService: AppService) {
    this.login();
  }

  ngOnInit() {
    console.log(this.location.hostname);
    this.appService.baseUrl = 'http://' + this.location.hostname + '/api/';
    this.appService.urls.subLink = 'http://' + this.location.hostname;
  }
  login() {
    const email = localStorage.getItem('email');
    const passwd = localStorage.getItem('passwd');
    this.appService.baseUrl = localStorage.getItem('baseUrl') + '/api/';
    this.appService.urls.subLink = localStorage.getItem('baseUrl');
    this.appService.post(this.appService.urls.login, {email: email, passwd: passwd}).subscribe((resp: any) => {
      localStorage.setItem('baseUrl', 'http://' + this.location.hostname);
      const userInfo = resp.body;
      if (userInfo.ret === 1) {
        localStorage.setItem('token', userInfo.data.token);
        localStorage.setItem('user_id', userInfo.data.user_id);
        localStorage.setItem('status', 'off');
        this.router.navigate(['home']).catch();
      } else {
        this.show = true;
      }
    }, () => {
      localStorage.setItem('baseUrl', 'http://' + this.location.hostname);
      this.appService.baseUrl = 'http://' + this.location.hostname + '/api/';
      this.appService.urls.subLink = 'http://' + this.location.hostname;
      this.show = true;
    });
  }
  enterToRegister() {
    this.router.navigate(['register']).catch();
  }
  enterToLogin() {
    this.router.navigate(['login']).catch();
  }
}
